#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
修复Python 2到Python 3的语法兼容性问题
"""

import os
import re

def fix_except_syntax():
    """修复except Exception, e: 语法为 except Exception as e:"""
    
    # 遍历apps目录中的所有Python文件
    for root, dirs, files in os.walk('apps'):
        for file in files:
            if file.endswith('.py'):
                file_path = os.path.join(root, file)
                
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        content = f.read()
                    
                    original_content = content
                    
                    # 修复except语法
                    # 匹配 except XXXError, e: 或 except Exception, e: 等模式
                    content = re.sub(
                        r'except\s+([A-Za-z_][A-Za-z0-9_\.]*)\s*,\s*([A-Za-z_][A-Za-z0-9_]*)\s*:',
                        r'except \1 as \2:',
                        content
                    )
                    
                    # 如果内容有变化，写回文件
                    if content != original_content:
                        with open(file_path, 'w', encoding='utf-8') as f:
                            f.write(content)
                        print(f"修复了 {file_path}")
                        
                except Exception as e:
                    print(f"处理 {file_path} 时出错: {e}")

def fix_specific_files():
    """修复特定的已知问题文件"""
    
    specific_fixes = [
        # xadmin相关文件
        ('apps/xladmin/util.py', 'except models.ProtectedError, e:', 'except models.ProtectedError as e:'),
        ('apps/xladmin/plugins/filters.py', 'except ValidationError, e:', 'except ValidationError as e:'),
        ('apps/xladmin/plugins/filters.py', 'except FieldDoesNotExist, e:', 'except FieldDoesNotExist as e:'),
        ('apps/xladmin/plugins/filters.py', 'except Exception, e:', 'except Exception as e:'),
        ('apps/xladmin/views/dashboard.py', 'except Exception, e:', 'except Exception as e:'),
        
        # 其他应用
        ('apps/productcatalog/adminx.py', 'except ImportError, e:', 'except ImportError as e:'),
        ('apps/productcatalog/_admin.py', 'except ImportError, e:', 'except ImportError as e:'),
        ('apps/technologies/views_ajax.py', 'except Exception, e:', 'except Exception as e:'),
        ('apps/technologies/views.py', 'except Exception, e:', 'except Exception as e:'),
    ]
    
    for file_path, old_text, new_text in specific_fixes:
        if os.path.exists(file_path):
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                
                if old_text in content:
                    content = content.replace(old_text, new_text)
                    
                    with open(file_path, 'w', encoding='utf-8') as f:
                        f.write(content)
                    print(f"修复了 {file_path}")
                    
            except Exception as e:
                print(f"修复 {file_path} 时出错: {e}")

if __name__ == '__main__':
    print("=== 修复Python 3语法兼容性 ===")
    
    print("\n1. 批量修复except语法...")
    fix_except_syntax()
    
    print("\n2. 修复特定文件...")
    fix_specific_files()
    
    print("\n=== 修复完成 ===") 